import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';

enum NetworkState {
  none,
  loading, // 加载中
  success, // 成功
  error, // 失败
}

class BaseController extends GetxController {
  void initConfig() {}
  bool btnEnableRule() => false;

  final _netState = NetworkState.none.obs;

  NetworkState get netState => _netState.value;

  // 错误信息
  final _errorMessage = ''.obs;

  String get errorMessage => _errorMessage.value;
  Future<void> Function()? request;
  @override
  void onInit() {
    initConfig();
    requestOfService(request: request);
    super.onInit();
  }

  requestOfService(
    {
      Future<void> Function()? request
  }) async {
    try {
      _updateNetworkState(NetworkState.loading);
      // 执行请求
      if(this.request != null){
        await this.request!();
      }
      // 更新为成功状态
      _updateNetworkState(NetworkState.success);
    } catch (e,stackTrace) {
      // 更新为错误状态
      print('Error: $e');
      print('Stack trace: $stackTrace');
      // 提取并打印错误发生的文件和行号
      final lines = stackTrace.toString().split('\n');
      if (lines.isNotEmpty) {
        print('Error occurred at: ${lines[0]}');
      }
      _updateNetworkState(NetworkState.error, errorMessage: e.toString());
    }
  }

  // 更新网络状态
  void _updateNetworkState(NetworkState state, {String errorMessage = ''}) {
    _netState.value = state;
    _errorMessage.value = errorMessage;
  }
}
